import configparser
import os
from config import settings
from log.logUtils import logger

current_dir = settings.TEST_CONFIG

class ReadConfig(object):
    '''配置参数'''

    def __init__(self):
        '''
        用法：
        conf = ReadConfig()
        confinfo = conf.getconf("url")
        '''
        # 设置conf.ini路径
        current_dir = os.path.dirname(__file__)
        # top_one_dir = os.path.dirname(current_dir)
        top_one_dir = os.path.dirname(os.path.dirname(__file__))
        file_name = top_one_dir + "/config/config.conf"
        # 实例化ConfigParser对象
        self.config = configparser.ConfigParser()
        self.config.read(file_name, encoding='utf-8')
        # 特殊字符
        self.cf_rawConfig = configparser.RawConfigParser()
        self.cf_rawConfig.read(file_name, encoding='utf-8')

    def getRawConfig(self, mainKey, keyname):
        self.info = self.cf_rawConfig.get(mainKey, keyname)
        if not self.info:
            logger.debug("ReadConfig()没有找到config文件对应的key")
            raise configparser.NoOptionError(keyname, mainKey)
        return self.info

    def getconf(self, mainKey, keyname):
        self.info = self.config.get(mainKey, keyname)
        if not self.info:
            logger.debug("ReadConfig()没有找到config文件对应的key")
            raise configparser.NoOptionError(keyname, mainKey)
        return self.info
        '''
        num = len(self.config.sections())
        i = 0
        logger.debug("num = %s", str(num))
        # 根据sections的数量进行循环查找keyname是否存在
        while i < num:
            # 每次循环获取对应list中的section
            section = self.config.sections()[i]
            # 如果keyname存在section中，则输出其参数值
            if keyname in self.config.options(section):

                logger.debug("num --> %s", str(i))
                logger.debug("section ---> %s", section)
                logger.debug("keyname ---> %s", keyname)

                if not self.config.get(section, keyname):
                    break
                self.info = self.config.get(section, keyname)
                i += 1
            else:
                i += 1
                logger.debug("ReadConfig()没有找到config文件对应的key")
        return self.info
        '''


conf = ReadConfig()

if __name__ == "__main__":
    logger.debug(1123)
    logger.debug(os.path.dirname(__file__))
    logger.debug(os.path.dirname(os.path.dirname(__file__)))
    base_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    logger.debug("base_dir =====: %s" ,base_dir)
    path = os.path.join(base_dir, '123.txt')
    logger.debug("base_dir =====: %s " , path)
    ke = os.path.join(base_dir, "config", "config.conf")
    logger.debug(' ke, ====2222==== : %s', ke)

    conf = ReadConfig()
    confinfo = conf.getconf("login", "login_phone")
    logger.debug("config --- > %s", confinfo)
